<?php

namespace App\Console\Commands\Test\RabbmitMQ\Rpc;

use Illuminate\Console\Command;

use PhpAmqpLib\Connection\AMQPStreamConnection;


class Server extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'rabbitMQ:receive-topic {type*}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }


    public function handle()
    {

        try {
            $connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');

            $channel = $connection->channel();

            $channel->exchange_declare('topic_logs', 'topic', false, false, false);

            list($queue_name ,, ) = $channel->queue_declare("", false, false, true, false);


            $binding_keys = $this->argument('type') ?: ['#'];

            foreach ($binding_keys as $binding_key) {
                $channel->queue_bind($queue_name, 'topic_logs', $binding_key);
                $this->info("[rabbitMQ start direct-{$binding_key}]等待消息。 退出按CTRL + C");
            }

            // $channel->basic_qos(null, 1, null);

            $channel->basic_consume($queue_name, '', false, true, false, false, function ($msg) {
                $this->info('[rabbitMQ receive]收到消息----'. $msg->body );
            });

            while(count($channel->callbacks)) {
                $channel->wait();
            }

            $channel->close();
            $connection->close();

        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }

    }
}
